<script setup lang="ts">
import { onMounted, ref, shallowRef, watch, watchEffect } from "vue";
import * as echarts from "echarts";
import { storeToRefs } from "pinia";
import anime from "animejs";
import { fitChartSize } from "@/utils/responsible";
import { DATE_FORMAT } from "@/const";
import { useCityRoadStore } from "@/store/city-road";
import { charts } from "@/services/city-road";
import markerHeader from "@/assets/green-wave/marker_header@2x.png";

const tabs = [
    {
        value: 1,
        label: "路段速度",
    },
    {
        value: 2,
        label: "路口速度",
    },
    {
        value: 3,
        label: "超速",
    },
    {
        value: 4,
        label: "降速",
    },
];

const indexType = ref(tabs[0].value);
const containerElRef = ref(null);
const chartEl = ref(null);
const chartRef = shallowRef<null | echarts.ECharts>(null);

const store = useCityRoadStore();
const { currentRoad, weekRange, dateType } = storeToRefs(store);

store.$onAction(async ({ name, args }) => {
    if (name !== "updateRoad" || !containerElRef.value) return;

    if (!args[0]) {
        // 即将关闭
        anime({
            targets: containerElRef.value,
            opacity: [1, 0],
            duration: 200,
            translateX: ["-50%", "-50%"],
            translateY: [0, fitChartSize(261)],
            easing: "easeInOutQuad",
        });
    } else if (!currentRoad.value && args[0]) {
        // 即将打开
        anime({
            targets: containerElRef.value,
            opacity: [0, 1],
            duration: 200,
            translateX: ["-50%", "-50%"],
            translateY: [fitChartSize(261), 0],
            easing: "easeInOutQuad",
        });
    }
});

watch(currentRoad, (v) => {
    if (!v) {
        anime({
            targets: containerElRef.value,
            opacity: [1, 0],
            duration: 200,
            translateX: ["-50%", "-50%"],
            translateY: [0, fitChartSize(261)],
            easing: "easeInOutQuad",
        });
    }
});

function change(tab: number) {
    indexType.value = tab;
}

function updateChart(res: any) {
    const { axis = [], data = [] } = res || {};

    const markArea = axis
        ?.map((e: any) => {
            if (e?.length === 2) {
                return [{ xAxis: e[0] }, { xAxis: e[1] }];
            }
            return [];
        })
        .filter((e: any) => e.length === 2);
    const label = tabs.find((item) => item.value === indexType.value);
    const series = [
        {
            name: label,
            data: data,
            type: "line",
            smooth: true,
        },
    ];

    chartRef.value?.setOption(
        {
            grid: { top: "2%", left: "4%", right: "4%", bottom: "30%" },
            tooltip: { trigger: "axis" },
            xAxis: { type: "category", data: axis },
            yAxis: {
                type: "value",
                splitLine: {
                    lineStyle: {
                        type: "dashed",
                        color: "rgba(216,216,216,0.3)",
                    },
                },
            },
            dataZoom: [
                {
                    startValue: markArea[0]?.[0]?.xAxis,
                    endValue: markArea[0]?.[1]?.xAxis,
                    height: fitChartSize(20),
                    bottom: "8%",
                },
            ],
            series,
        },
        { notMerge: true }
    );
}
const { startTime, endTime } = storeToRefs(store);

watchEffect(async () => {
    if (!currentRoad.value?.id || weekRange.value?.length !== 2) {
        return;
    }
    const [start, end] = weekRange.value;
    let res = null;
    try {
        res = await charts({
            beginTime:
                start?.format(DATE_FORMAT) + " " + startTime.value + ":00",
            endTime: end?.format(DATE_FORMAT) + " " + endTime.value + ":00",
            roadId: currentRoad.value.id,
            dateType: dateType.value,
            indexType: indexType.value,
            roadsegId: currentRoad.value.roadsegId,
        });
    } catch (error) {
        res = null;
    }
    updateChart(res);
});

onMounted(() => {
    const chart = echarts.init(chartEl.value, { theme: "dark" });
    chartRef.value = chart;
});
</script>

<template>
    <div ref="containerElRef" class="container">
        <div class="head">
            <h5 class="marker_header_roadName">
                <img :src="markerHeader" alt="" />{{ currentRoad?.name }}
            </h5>
            <h6>{{ currentRoad?.roadsegName }}</h6>
            <ul class="tabs">
                <li
                    class="tab"
                    :class="{ active: indexType === tab.value }"
                    v-for="tab in tabs"
                    :key="tab.value"
                    @click="change(tab.value)"
                >
                    {{ tab.label }}
                </li>
            </ul>
        </div>
        <div ref="chartEl" class="chart"></div>
        <el-icon
            class="btn-close"
            :color="'rgba(2, 163, 255, 1)'"
            :size="fitChartSize(28)"
            @click="store.updateRoad(null)"
            ><CircleCloseFilled
        /></el-icon>
    </div>
</template>

<style lang="scss" scoped>
.container {
    z-index: $drawerIndex + 1;
    position: fixed;
    bottom: 0;
    display: flex;
    flex-direction: column;
    width: 1158px;
    height: 261px;
    padding: 16px 80px 24px 68px;
    left: 50%;
    opacity: 0;
    transform: translate(-50%, 261px);
    background: url(@/assets/green-wave/bg_popup.png) no-repeat;
    background-size: cover;
    color: #fff;

    .btn-close {
        position: absolute;
        top: -4px;
        right: 40px;
        cursor: pointer;
    }

    .head {
        position: relative;
        margin-bottom: 14px;
        font-size: 16px;
        .marker_header_roadName {
            display: flex;
            align-items: center;
            font-weight: 600;
            font-size: 16px;
            color: #ffffff;
            line-height: 22px;
            text-align: left;
            img {
                width: 30px;
            }
        }
        h5 {
            font-weight: 600;
        }
        h6 {
            color: #4bc6ff;
            font-size: 14px;
            padding-left: 10px;
        }
        .tabs {
            position: absolute;
            top: 0;
            left: 50%;
            transform: translateX(-50%);
            overflow: hidden;
            display: flex;
            font-size: 13px;
            border-radius: 4px;
            background: url(@/assets/bg_button_group.png) no-repeat left center/
                100% 100%;
            .tab {
                list-style: none;
                padding: 3px 9px;
                cursor: pointer;
                color: #0fb2ff;
                &.active {
                    color: #fff;
                    background: #0f3d5e;
                    box-shadow: inset 0px 0px 6px 0px rgba(0, 170, 255, 0.9);
                }
            }
        }
    }
    .chart {
        flex: 1;
    }
}
</style>
